package com.pm2.service.impl;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pm2.dao.project.TaskAttachmentDao;
import com.pm2.entity.weekMeet.TaskAttachment;
import com.pm2.entity.weekMeet.TaskAttachmentVo;
import com.pm2.service.project.TaskAttachmentService;
@Service
@Transactional
public class TaskAttachmentServiceImpl implements TaskAttachmentService {
    @Autowired
    private TaskAttachmentDao taskAttachmentDao;
	@Override
	public void saveOrUpdate(TaskAttachment t) {
		taskAttachmentDao.save(t);

	}
	@Override
	public void save(List<TaskAttachment> list) {
		taskAttachmentDao.save(list);
		
	}
	@Override
	public List<TaskAttachment> getAllFileByTaskId(int id) {
		// TODO Auto-generated method stub
		return taskAttachmentDao.findByTaskId(id);
	}
	@Override
	public List<TaskAttachmentVo> getFileByTaskId(int id) {
		List<Object[]> list = taskAttachmentDao.findFileByTaskId(id);
		List<TaskAttachmentVo> testViews = null;
    	try {
    		if(list.size()>0) {
    			testViews = castEntity(list, TaskAttachmentVo.class);
    		}else {
    			testViews = new ArrayList<TaskAttachmentVo>();
    		}
    		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return testViews;
	}
	
	//转换实体类
    public static <T> List<T> castEntity(List<Object[]> list, Class<T> clazz) throws Exception {
        List<T> returnList = new ArrayList<T>();
        Object[] co = list.get(0);
        Class[] c2 = new Class[co.length];

        //确定构造方法
        for (int i = 0; i < co.length; i++) {
            c2[i] = co[i].getClass();
        }

        for (Object[] o : list) {
            Constructor<T> constructor = clazz.getConstructor(c2);
            returnList.add(constructor.newInstance(o));
        }

        return returnList;
    }

}
